# =============================================================================
#'
#' @title Write Keyword
#'
#' @description Write keyword into GEOtop parameter file
#'
#' @details This function writes a keyword into a loaded GEOtop 
#' parameter-file string. If the keyword exists already in the 
#' parameter-file string, then its value is changed. If it does not 
#' exist, a new line with the keyword and its value are inserted.
#'
#' @param spath The simulation path. This is the directory that holds the 
#' GEOtop parameter file and that is passed to GEOtop upon execution.
#' @param keyword Name of the GEOtop keyword to be modified or appended.
#' @param value Value for keyword to insert. This can be a scalar or a 
#' vector.
#' @param type Keyword type, either "NUMERIC" (default) or "STRING".
#' @param comment Optional comment that is written to the first line of the
#' new file
#' @param env List that passes a number of default settings.
#' @export
#' @examples
#' fs <- KeywordWrite("./data", "DtPlotPoint", 1, type = "NUMERIC", env = SetEnv()) 
#'
#' @author Stephan Gruber <stephan.gruber@@carleton.ca>
#'
# =============================================================================
KeywordWrite <- function(spath, keyword, value, type = "NUMERIC", 
                         comment = "", env = SetEnv()) { 

  #read into file string
  fs <- readLines(file.path(spath, env$parfile)) 
  
  if (toupper(type) == "STRING") {
    vs <- paste(env$quochar, value, env$quochar,sep="")
  } else {
    #convert to character
    vs <- as.character(value)  
  }
  
  #check if character string is vector or scalar
  if (length(value) > 1) value <- paste(value, sep = "", collapse = env$vecchar)
  
  #find line
  ln <- KeywordFindLine(fs, keyword, env = env)
  
  if (is.na(ln) == FALSE) { #insert into existing line
    fs <- KeywordWriteLine(fs, ln, value, env = env)
  } else { #if line does not exist, append at end
    line <- paste(keyword, env$splchar, value, sep="")
    fs   <- c(fs, line)
  }
  
  #write
  con <- file(file.path(spath, env$parfile, fsep = .Platform$file.sep), "w")
  if (comment != "") {
    cat(env$comchar, comment, '\n', file = con, sep="")	
  }
  cat(fs, file = con, sep='\n')
  close(con)
}
